class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end

  # rescue_from CanCan::AuthorizationNotPerformed do|exception|
  #   redirect_to root_url, :alert => exception.message
  # end

  #强制所有的控制器动作使用权限认证
  #check_authorization :unless => :devise_controller?
  private

  #修改ability.rb的默认参数，当然，前提是在形参中声明了。
  def current_ability
    @current_ability ||= Ability.new(current_user, options: {request: request} )
  end

  protected
  def self.permission
    return name = controller_name.classify.constantize
  end


  def setup_actions_controllers_db
    write_permission("all", "manage", "Everything", "All operations", true)
    controllers = Dir.new("#{Rails.root}/app/controllers").entries #获取此目录下的所有文件
    controllers.each do |controller|
      if controller =~ /_controller/
        foo_bar = controller.camelize.gsub(".rb","").constantize.new
      end
    end


  end

  def eval_cancan_action(action)
    cancan_action=nil
    action_desc=nil
    case action.to_s
      when "index", "show", "search"
        cancan_action = "read"
        action_desc = I18n.t :read
      when "create", "new"
        cancan_action = "create"
        action_desc = I18n.t :create
      when "edit", "update"
        cancan_action = "update"
        action_desc = I18n.t :edit
      when "delete", "destroy"
        cancan_action = "delete"
        action_desc = I18n.t :delete
      else
        cancan_action = action.to_s
        action_desc = "Other: " << cancan_action
    end
    return action_desc, cancan_action

  end


  def write_permission(class_name, cancancan_action, name, description, force_id_1=false)
    permission= Permission.where("subject_class = ? and action = ?", class_name, cancancan_action)
    if not permission
      permission = Permission.new
      permission.id = 1 if force_id_1
      permission.subject_class= class_name
      permission.action= cancancan_action
      permission.name= name
      permission.description= description
      permission.save
    else
      permission.name= name
      permission.description= description
      permission.save
    end
  end
end
